﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DIProject.Dictionary
{
    public partial class Link : Form
    {
        public string startuptext = string.Empty;
        private Int32 goodsid_searching = int.MinValue;

        public Link()
        {
            InitializeComponent();
        }
        public Int32 ContragentId
        {
            get
            {
                if (cbContragents.Items.Count < 1)
                {
                    return Int32.MinValue;
                }
                return (Int32)cbContragents.ComboBox.SelectedValue;
            }
        }

        private void Link_Load(object sender, EventArgs e)
        {
            DataSets.SettingsTableAdapters.ContragentsTableAdapter adapter = new DIProject.DataSets.SettingsTableAdapters.ContragentsTableAdapter();
            DataSets.Settings.ContragentsDataTable cdt = adapter.GetData();
            DataSets.Settings.ContragentsRow cr = cdt.NewContragentsRow();
            cr.Id = Int32.MinValue;
            cr.Name = "Выберите поставщика";
            cr.ShortName = "ВП";
            cdt.Rows.InsertAt(cr, 0);
            cbContragents.ComboBox.DisplayMember = "Name";
            cbContragents.ComboBox.ValueMember = "Id";
            cbContragents.ComboBox.DataSource = cdt;
            txbFilter.Text = startuptext;
        }
        private DataSets.Dictionary.LinkDataTable data = null;
        private DataSets.Dictionary.Link1DataTable data1 = null;
        private Int32 Count
        {
            get
            {
                if (data == null)
                    return 0;
                return data.DefaultView.Count+1;
            }
        }
        private Int32 Count1
        {
            get
            {
                if (data1 == null)
                    return 0;
                return data1.DefaultView.Count + 1;
            }
        }

        private void cbContragents_SelectedIndexChanged(object sender, EventArgs e)
        {
            Int32 sValue = (Int32)cbContragents.ComboBox.SelectedValue;
            if (sValue == Int32.MinValue)
            {
                lblStatus.Text = string.Empty;
                data = null;
                return;
            }            
            DataSets.DictionaryTableAdapters.LinkTableAdapter lnk = new DIProject.DataSets.DictionaryTableAdapters.LinkTableAdapter();
            DataSets.DictionaryTableAdapters.Link1TableAdapter lnk1 = new DIProject.DataSets.DictionaryTableAdapters.Link1TableAdapter();
            data = lnk.GetData(sValue);
            data1 = lnk1.GetData(sValue);
            
            //dgvLinls.DataSource = data;
            lblStatus.Text = "Всего " + this.Count.ToString();
            dgvLinls.Rows.Clear();
            if (this.Count > 0)
                dgvLinls.RowCount = this.Count;
            else
                dgvLinls.RowCount = 1;
            
            dgvFndErrorGrid.Rows.Clear();
            if (this.Count > 0)
                dgvFndErrorGrid.RowCount = this.Count1;
            else
                dgvFndErrorGrid.RowCount = 1;

            if (txbFilter.Text.Length > 0)
                toolStripButton1.PerformClick();
        }

        private void dgvLinls_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
        {
            if (e.RowIndex+1 >= this.Count)
                return;
            if (data == null)
                return;
            Int32 colInd = e.ColumnIndex;
            if (data.Columns.Count <= colInd)
                return;
            Int32 rowInd = e.RowIndex;
            if (data.Count <= rowInd)
                return;
            e.Value = data.DefaultView[rowInd][colInd];

        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            lblStatus.Text = string.Empty;
            if (data == null)
                return;
            if (string.IsNullOrEmpty(txbFilter.Text))
            {
                data.DefaultView.RowFilter = string.Empty;
                dgvLinls.Rows.Clear();
                dgvLinls.RowCount = this.Count;
                return;
            }
            int gid_search = int.MinValue;
            try { goodsid_searching = Convert.ToInt32(txbFilter.Text); }
            catch { }
            if (goodsid_searching != int.MinValue)
            {
                if (MessageBox.Show("Выполнить поиск по идентификатору?", "Поиск",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                    goodsid_searching = int.MinValue;
            }

            string tmp = txbFilter.Text.Replace("'", "''");
            if (goodsid_searching != int.MinValue)
                data.DefaultView.RowFilter = "innerId=" + txbFilter.Text;
            else
                data.DefaultView.RowFilter = "innerName like " + "'*" + txbFilter.Text + "*'" + " OR outerName like " + "'*" + txbFilter.Text + "*'";

            dgvLinls.Rows.Clear();
            dgvLinls.RowCount = this.Count;
            lblStatus.Text = "Всего " + this.Count.ToString();
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgvLinls.SelectedRows.Count < 1)
            {
                MessageBox.Show("Необходимо выделить строку");
                return;
            }
            DataGridViewRow row = dgvLinls.SelectedRows[0];
            Int32 linkId = (Int32)row.Cells[4].Value;
            DateTime mD = (DateTime)row.Cells[10].Value;
            string tmp = (string)row.Cells[1].Value;
            DataSets.Dictionary.LinkRow lr = data.FindBylinkId(linkId);
            if (lr == null)
            {
                MessageBox.Show("Не найдена строка в данных");
                return;
            }
            DialogResult dRes = MessageBox.Show("Удалить перекодировку для " + tmp, "Вопрос", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if(dRes!= DialogResult.OK)
                return;
            try
            {
                DIProject.Data.Links.DeleteLink(linkId, mD);
                lr.Delete();
                data.AcceptChanges();
                dgvLinls.Rows.Clear();
                dgvLinls.RowCount = this.Count;
                lblStatus.Text = "Всего " + this.Count.ToString();
            }
            catch (Exception ee)
            {
                MessageBox.Show("Не удалось удалить строку");
            }
            MessageBox.Show("Перекодировка успешно удалена!", "Успех!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //DialogResult dr = MessageBox.Show("Удалить
        }

        private void updateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataGridViewRow row = dgvLinls.SelectedRows[0];
            Int32 linkId = (Int32)row.Cells[4].Value;
            DateTime mD = (DateTime)row.Cells[10].Value;
            string tmp = (string)row.Cells[1].Value;
            
            int indexof = tmp.IndexOf(' ', 0);
            if (indexof == -1) indexof = tmp.Length;
            tmp = tmp.Substring(0, indexof);
            
            DataSets.Dictionary.LinkRow lr = data.FindBylinkId(linkId);
            if (lr == null)
            {
                MessageBox.Show("Не найдена строка в данных");
                return;
            }
            LincUpdate lu = new LincUpdate(lr, this.ContragentId);
            lu.startuptext = tmp;
            if (lu.ShowDialog(this) == DialogResult.OK)
            {
                MessageBox.Show("Перекодировка изменена");
            }
        }

        private void dgvLinls_MouseMove(object sender, MouseEventArgs e)
        {
            if (!mousSelectFlag.Checked)
                return;
            DataGridView.HitTestInfo hit = dgvLinls.HitTest(e.X, e.Y);
            if (hit.Type == DataGridViewHitTestType.Cell)
                dgvLinls.Rows[hit.RowIndex].Selected = true;
        }

        private void Link_Shown(object sender, EventArgs e)
        {
            if (startuptext.Length > 0)
                toolStripButton1.PerformClick();
        }

        private void txbFilter_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                toolStripButton1.PerformClick();
            }
        }

        private void finderrors_toolstripbutton_Click(object sender, EventArgs e)
        {
            bool FNDERR = false;
            /*
            if (dgvFndErrorGrid.Visible == false)
            {
                dgvLinls.Visible = false;
                dgvFndErrorGrid.Visible = true;
                finderrors_toolstripbutton.Text = "Обычная таблица";
                // Прогоняем искалку
                DataGridViewRow dgvr_prev = null;
                int innerId, innerId_prev, outerId, outerId_prev;
                dgvErrorsOnly.Rows.Add("GoodsId", "Наименование", "Производитель", "Страна", "Код поставщика", "Наименование поставщика", "Страна", "Производитель", "ID перекодировки");
                foreach (DataGridViewRow dgvr in dgvFndErrorGrid.Rows)
                {
                    if (dgvr_prev == null)
                    {
                        dgvr_prev = dgvr;
                        continue;
                    }
                    // сверка
                    innerId = Convert.ToInt32(dgvr.Cells["dataGridViewTextBoxColumn1"].Value);
                    innerId_prev = Convert.ToInt32(dgvr_prev.Cells["dataGridViewTextBoxColumn1"].Value);
                    outerId = Convert.ToInt32(dgvr.Cells["dataGridViewTextBoxColumn9"].Value);
                    outerId_prev = Convert.ToInt32(dgvr_prev.Cells["dataGridViewTextBoxColumn9"].Value);
                    if (innerId != innerId_prev && 
                            outerId == outerId_prev)
                    { 
                        // нашли проблемную запись! прайс один а коды разные
                        dgvr.DefaultCellStyle.BackColor = Color.Red;
                        dgvr_prev.DefaultCellStyle.BackColor = Color.Red;
                        dgvErrorsOnly.Rows.Add(dgvr.Cells["dataGridViewTextBoxColumn1"].Value,
                                               dgvr.Cells["dataGridViewTextBoxColumn2"].Value,
                                               dgvr.Cells["dataGridViewTextBoxColumn3"].Value,
                                               dgvr.Cells["dataGridViewTextBoxColumn4"].Value,
                                               dgvr.Cells["dataGridViewTextBoxColumn9"].Value,
                                               dgvr.Cells["dataGridViewTextBoxColumn6"].Value,
                                               dgvr.Cells["dataGridViewTextBoxColumn7"].Value,
                                               dgvr.Cells["dataGridViewTextBoxColumn8"].Value,
                                               dgvr.Cells["dataGridViewTextBoxColumn5"].Value);
                        dgvErrorsOnly.Rows.Add(dgvr_prev.Cells["dataGridViewTextBoxColumn1"].Value,
                                               dgvr_prev.Cells["dataGridViewTextBoxColumn2"].Value,
                                               dgvr_prev.Cells["dataGridViewTextBoxColumn3"].Value,
                                               dgvr_prev.Cells["dataGridViewTextBoxColumn4"].Value,
                                               dgvr_prev.Cells["dataGridViewTextBoxColumn9"].Value,
                                               dgvr_prev.Cells["dataGridViewTextBoxColumn6"].Value,
                                               dgvr_prev.Cells["dataGridViewTextBoxColumn7"].Value,
                                               dgvr_prev.Cells["dataGridViewTextBoxColumn8"].Value,
                                               dgvr_prev.Cells["dataGridViewTextBoxColumn5"].Value);

                        FNDERR = true;
                    }
                    dgvr_prev = dgvr;
                }
            }
            else
            {
                dgvFndErrorGrid.Visible = false;
                dgvLinls.Visible = true;                
                finderrors_toolstripbutton.Text = "Поиск ошибок";
            }
            if (FNDERR)
                MessageBox.Show("Ошибки есть!");*/
            DataGridViewRow dgvr_prev = null;
            int innerId, innerId_prev, outerId, outerId_prev;
            foreach (DataGridViewRow dgvr in dgvLinls.Rows)
            {
                if (dgvr_prev == null)
                {
                    dgvr_prev = dgvr;
                    continue;
                }
                // сверка
                innerId = Convert.ToInt32(dgvr.Cells["innerIdDataGridViewTextBoxColumn"].Value);
                innerId_prev = Convert.ToInt32(dgvr_prev.Cells["innerIdDataGridViewTextBoxColumn"].Value);
                outerId = Convert.ToInt32(dgvr.Cells["outerIdDataGridViewTextBoxColumn"].Value);
                outerId_prev = Convert.ToInt32(dgvr_prev.Cells["outerIdDataGridViewTextBoxColumn"].Value);
                if (innerId != innerId_prev && outerId == outerId_prev)
                {
                    // нашли проблемную запись! прайс один а коды разные
                    // дополнение - прокатываем агрегированность
                    FNDERR = true;
                    /*
                    aggregatedGoodsTableAdapter.Fill(this.dictionary.AggregatedGoods, innerId);
                    
                    foreach (DataSets.Dictionary.AggregatedGoodsRow agrow in dictionary.AggregatedGoods)
                    {
                        if (agrow.Id == innerId_prev)
                        {
                            FNDERR = true;
                            break;
                        }
                    }*/
                    //if (!FNDERR)
                    {
                        dgvr.DefaultCellStyle.BackColor = Color.Red;
                        dgvr_prev.DefaultCellStyle.BackColor = Color.Red;
                    }
                }
                dgvr_prev = dgvr;
            }//for
            if (FNDERR) MessageBox.Show("Ошибки есть");
        }

        private void dgvFndErrorGrid_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
        {
            if (e.RowIndex + 1 >= this.Count1)
                return;
            if (data1 == null)
                return;
            Int32 colInd = e.ColumnIndex;
            if (data1.Columns.Count <= colInd)
                return;
            Int32 rowInd = e.RowIndex;
            if (data1.Count <= rowInd)
                return;
            e.Value = data1.DefaultView[rowInd][colInd];
        }

        private void ErrListtoolStripButton2_Click(object sender, EventArgs e)
        {
            dgvFndErrorGrid.Visible = false;
            dgvLinls.Visible = false;
            dgvErrorsOnly.Visible = true;
            finderrors_toolstripbutton.Text = "Поиск ошибок";
        }     
    }
}